package com.j.lemon.learn.thread.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

public class NIOClient {
    private Selector selector;
    public void init(String ip,int port) throws IOException{
        SocketChannel channel=SocketChannel.open();
        channel.configureBlocking(false);
        this.selector= SelectorProvider.provider().openSelector();
        channel.connect(new InetSocketAddress(ip,port));
        channel.register(selector, SelectionKey.OP_CONNECT);

    }
    public void working() throws IOException, InterruptedException {
        init("localhost",8082);
        while(true){
            if(!selector.isOpen()){
                break;
            }
            selector.select();
            Iterator<SelectionKey> ite=this.selector.selectedKeys().iterator();
            while(ite.hasNext()){
                SelectionKey key=ite.next();
                ite.remove();
                if(key.isConnectable()){
                    connect(key);
                }else if(key.isReadable()){
                    read(key);
                }else if (key.isWritable()){
                    write(key);
                }
            }
        }
    }

    public void connect(SelectionKey key) throws IOException, InterruptedException {
        SocketChannel channel= (SocketChannel) key.channel();
        if(channel.isConnectionPending()){
            channel.finishConnect();
        }
        channel.configureBlocking(false);
//        Thread.sleep(50000);
        //channel.write(ByteBuffer.wrap(new String("hello server~\r\n").getBytes()));
        channel.register(selector,SelectionKey.OP_WRITE);
    }

    public void write(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();
        channel.write(ByteBuffer.wrap(new String("hello server~\r\n").getBytes()));
        key.interestOps(SelectionKey.OP_READ);
    }
    public void read(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();
        long e = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocate(100);
        channel.read(buffer);
        byte [] data = buffer.array();
        String msg = new String(data).trim();
        long a = System.currentTimeMillis();
        System.out.println("spend:"+(a-e)+"ms");
        System.out.println("客户端收到消息："+msg);
        channel.close();
        key.selector().close();
    }

}
